package com.nanyang.tms.manager.bill.handler;

import cn.hutool.core.util.ObjectUtil;
import com.nanyang.common.core.dict.CommonEnum;
import com.nanyang.common.core.flow.context.TransHandlerContext;
import com.nanyang.common.core.flow.handler.AbstractTransHandler;
import com.nanyang.common.tool.utils.convert.BeanUtils;
import com.nanyang.tms.common.exception.TmsManagerException;
import com.nanyang.tms.dao.bill.BillRecordDao;
import com.nanyang.tms.dao.waybill.WaybillDao;
import com.nanyang.tms.domain.bill.BillRecordVO;
import com.nanyang.tms.domain.bill.context.BillUpdateContext;
import com.nanyang.tms.domain.cost.context.CalculateCostFreightContext;
import com.nanyang.tms.domain.forecast.context.CalculateFreightContext;
import com.nanyang.tms.domain.waybill.WaybillVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class BillBuildHandler extends AbstractTransHandler {
    @Autowired
    private BillRecordDao billRecordDao;
    @Autowired
    private WaybillDao waybillDao;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        BillUpdateContext billUpdateContext = (BillUpdateContext)context.getInnerContext(BillUpdateContext.class);
        BillRecordVO billRecordVO = billRecordDao.selectByCode(billUpdateContext.getBillRecordCode());
        if(ObjectUtil.isEmpty(billRecordVO)){
            throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
        }
        WaybillVO waybillVO = waybillDao.selectByWaybillCode(billRecordVO.getWaybillCode());
        if(ObjectUtil.isEmpty(waybillVO)){
            throw new TmsManagerException(CommonEnum.NO_CONTENT.getCode(),CommonEnum.NO_CONTENT.getMessage());
        }
        BeanUtils.copyProperties(waybillVO, billUpdateContext);
        billUpdateContext.setIp(billRecordVO.getIp());
        billUpdateContext.setPin(billRecordVO.getGmtCreatePin());
        billUpdateContext.setSolveChargeWeight(billRecordVO.getRecordChargeWeight());
        billUpdateContext.setSolveVolumeWeight(billRecordVO.getRecordVolumeWeight());
        billUpdateContext.setSolveWeight(billRecordVO.getRecordWeight());
        CalculateFreightContext calculateFreightContext=(CalculateFreightContext) context.getInnerContext(CalculateFreightContext.class);
        BeanUtils.copyProperties(waybillVO, calculateFreightContext);
        calculateFreightContext.setTotalChargeWeight(billRecordVO.getRecordChargeWeight());
        CalculateCostFreightContext calculateCostFreightContext=(CalculateCostFreightContext) context.getInnerContext(CalculateCostFreightContext.class);
        BeanUtils.copyProperties(waybillVO, calculateCostFreightContext);
        calculateCostFreightContext.setTotalChargeWeight(billRecordVO.getRecordChargeWeight());
        return true;
    }
}
